import React, { useState, useEffect } from 'react';
import {
  Card,
  Form,
  Input,
  Select,
  Button,
  Checkbox,
  Row,
  Col,
  Divider,
  Typography,
  Space,
  Tag,
  Statistic,
  message,
  List,
  Popconfirm,
  Modal,
  Empty
} from 'antd';
import {
  CalculatorOutlined,
  CalendarOutlined,
  NumberOutlined,
  SettingOutlined,
  EyeOutlined,
  PlusOutlined,
  DeleteOutlined,
  HistoryOutlined,
  ExclamationCircleOutlined,
  CheckCircleOutlined
} from '@ant-design/icons';
import MatrixCalculator from './calc';
import DatabaseService from './database';
import errorMonitor from './errorMonitor';

// 创建测试函数
// 重新初始化数据库（修复createTime问题）
const reinitializeDatabase = async () => {
  try {
    console.log('开始重新初始化数据库...');
    await DatabaseService.reinitializeDatabase();
    message.success('数据库重新初始化完成，createTime问题已修复');
  } catch (error) {
    console.error('重新初始化数据库失败:', error);
    message.error('重新初始化数据库失败: ' + error.message);
  }
};

const testDiagnosisOrder = async () => {
    console.log('=== 测试诊断功能使用的历史数据顺序 ===');
    
    // 1. 测试原始数据库查询
    console.log('\n--- 测试原始orderBy查询 ---');
    try {
        const db = (await import('./database.js')).db;
        
        // 测试不同的排序方式
        console.log('1. 按createTime升序:');
        const ascRecords = await db.lotteryHistory.orderBy('createTime').toArray();
        ascRecords.forEach((record, index) => {
            console.log(`  ${index + 1}. ${record.issueno} - ${record.createTime} - ${record.opendate}`);
        });
        
        console.log('2. 按createTime升序后reverse:');
        const reverseRecords = await db.lotteryHistory.orderBy('createTime').reverse().toArray();
        reverseRecords.forEach((record, index) => {
            console.log(`  ${index + 1}. ${record.issueno} - ${record.createTime} - ${record.opendate}`);
        });
        
        console.log('3. 按createTime升序后reverse再limit(3):');
        const limitRecords = await db.lotteryHistory.orderBy('createTime').reverse().limit(3).toArray();
        limitRecords.forEach((record, index) => {
            console.log(`  ${index + 1}. ${record.issueno} - ${record.createTime} - ${record.opendate}`);
        });
        
    } catch (error) {
        console.error('直接数据库查询失败:', error);
    }
    
    // 2. 测试DatabaseService方法
    console.log('\n--- 测试DatabaseService.getRecentLotteryHistory(3) ---');
    const recentHistory = await DatabaseService.getRecentLotteryHistory(3);
    console.log('获取到的最新3期记录数量:', recentHistory.length);
    
    recentHistory.forEach((record, index) => {
        console.log(`第${index + 1}期:`, {
            期号: record.issueno,
            开奖日期: record.opendate,
            创建时间: record.createTime,
            时间戳: new Date(record.createTime).getTime()
        });
    });
    
    // 验证是否按时间倒序排列
    if (recentHistory.length >= 2) {
        const isCorrectOrder = new Date(recentHistory[0].createTime) >= new Date(recentHistory[1].createTime);
        console.log('时间排序是否正确(最新在前):', isCorrectOrder);
        
        if (!isCorrectOrder) {
            console.error('❌ 排序错误！第一条记录应该是最新的');
            console.log('第一条:', new Date(recentHistory[0].createTime).toISOString());
            console.log('第二条:', new Date(recentHistory[1].createTime).toISOString());
        } else {
            console.log('✅ 排序正确');
        }
    }
    
    // 3. 获取所有历史记录查看完整顺序
    console.log('\n--- 所有历史记录顺序 ---');
    const allHistory = await DatabaseService.getAllLotteryHistory();
    allHistory.forEach((record, index) => {
        console.log(`记录${index + 1}:`, {
            期号: record.issueno,
            开奖日期: record.opendate,
            创建时间: record.createTime,
            时间戳: new Date(record.createTime).getTime()
        });
    });
    
    // 4. 验证期号顺序
    console.log('\n--- 验证期号顺序 ---');
    const expectedOrder = ['2025006', '2025005', '2025004']; // 期望的顺序（最新到最早）
    const actualOrder = recentHistory.map(r => r.issueno);
    console.log('期望顺序:', expectedOrder);
    console.log('实际顺序:', actualOrder);
    
    const isOrderCorrect = JSON.stringify(expectedOrder) === JSON.stringify(actualOrder);
    console.log('期号顺序是否正确:', isOrderCorrect ? '✅ 正确' : '❌ 错误');
    
    if (!isOrderCorrect) {
        console.error('❌ 诊断功能可能使用了错误的历史数据顺序！');
        console.log('这会导致诊断功能分析最早的3期而不是最新的3期');
    }
};

const { Title, Text, Paragraph } = Typography;

const Calculator = () => {
  const [result, setResult] = useState(null);
  const [loading, setLoading] = useState(false);
  const [form] = Form.useForm();
  const [processedLuckyNumbers, setProcessedLuckyNumbers] = useState('');
  
  // 红蓝球状态
  const [redBalls, setRedBalls] = useState([null, null, null, null, null, null]);
  const [blueBall, setBlueBall] = useState(null);
  
  // 编辑状态
  const [editingBall, setEditingBall] = useState(null);
  const [editValue, setEditValue] = useState('');

  // 设备检测状态
  const [isMobile, setIsMobile] = useState(false);
  const [screenSize, setScreenSize] = useState('desktop');
  
  // 选号记录状态
  const [selections, setSelections] = useState([]);
  const [loadingSelections, setLoadingSelections] = useState(false);
  const [noteModalVisible, setNoteModalVisible] = useState(false);
  const [currentNote, setCurrentNote] = useState('');
  
  // 诊断相关状态
  const [diagnosisResult, setDiagnosisResult] = useState(null);
  const [diagnosisLoading, setDiagnosisLoading] = useState(false);
  const [showDiagnosisModal, setShowDiagnosisModal] = useState(false);
  
  // 可拖拽结果管理状态
  const [usedBalls, setUsedBalls] = useState([]); // 已使用的球（从可拖拽结果中移除）
  const [availableBalls, setAvailableBalls] = useState([]); // 当前可拖拽的球

  // 初始化加载
  useEffect(() => {
    loadSelections();
    
    // 监听选号记录清空事件
    const handlePickingRecordsCleared = () => {
      console.log('收到选号记录清空事件，重新加载计算器页面数据');
      loadSelections();
    };
    
    window.addEventListener('pickingRecordsCleared', handlePickingRecordsCleared);
    
    // 清理事件监听器
    return () => {
      window.removeEventListener('pickingRecordsCleared', handlePickingRecordsCleared);
    };
  }, []); 

  // 设备检测
  useEffect(() => {
    const checkDevice = () => {
      const width = window.innerWidth;
      setIsMobile(width < 768);
      if (width < 576) {
        setScreenSize('mobile');
      } else if (width < 768) {
        setScreenSize('tablet');
      } else {
        setScreenSize('desktop');
      }
    };

    checkDevice();
    window.addEventListener('resize', checkDevice);
    return () => window.removeEventListener('resize', checkDevice);
  }, []);

  // 处理幸运数字输入
  const handleLuckyNumbersChange = (e) => {
    const input = e.target.value;
    // 移除所有非数字字符
    const numbersOnly = input.replace(/[^0-9]/g, '');
    
    // 将连续数字按两位分组
    const pairs = [];
    for (let i = 0; i < numbersOnly.length; i += 2) {
      const pair = numbersOnly.slice(i, i + 2);
      if (pair.length === 2) {
        const num = parseInt(pair);
        // 确保在01-99范围内，排除00
        if (num >= 1 && num <= 99) {
          pairs.push(pair);
        }
      }
    }
    
    // 更新处理后的幸运数字显示
    setProcessedLuckyNumbers(pairs.join(','));
  };

  // 智能选号功能 - 使用双色球专用算法
  const handleSmartSelection = () => {
    const calculator = new MatrixCalculator();
    const formValues = form.getFieldsValue();
    
    try {
      console.log('开始智能选号，参数:', {
        dateInput: formValues.dateInput || "1",
        luckyNumbers: processedLuckyNumbers || "",
        weekday: formValues.weekday || "周二"
      });
      
      // 使用新的双色球算法
      const doubleBallResult = calculator.smartDoubleBall(
        formValues.dateInput || "1",
        processedLuckyNumbers || "",
        formValues.weekday || "周二"
      );
      
      console.log('智能选号结果:', doubleBallResult);
      
      // 验证结果
      if (!doubleBallResult || !doubleBallResult.redBalls || typeof doubleBallResult.blueBall !== 'number') {
        throw new Error('算法返回结果格式错误');
      }
      
      // 设置红球（确保在1-33范围内且来自计算结果）
      const validRedBalls = doubleBallResult.redBalls.filter(num => num >= 1 && num <= 33);
      if (validRedBalls.length === 0) {
        throw new Error('计算结果中没有红球范围(1-33)的数字，无法进行智能选号');
      }
      
      const newRedBalls = [null, null, null, null, null, null];
      validRedBalls.forEach((num, index) => {
        if (index < 6) {
          newRedBalls[index] = num;
        }
      });
      setRedBalls(newRedBalls);
      
      // 如果红球不足6个，给用户提示
      if (validRedBalls.length < 6) {
        message.warning(`计算结果中只有${validRedBalls.length}个红球范围的数字，已全部选中。建议调整参数重新计算。`);
      }
      
      // 设置蓝球（确保在1-16范围内）
      const validBlueBall = doubleBallResult.blueBall >= 1 && doubleBallResult.blueBall <= 16 
        ? doubleBallResult.blueBall 
        : ((doubleBallResult.blueBall % 16) + 1);
      setBlueBall(validBlueBall);
      
      // 显示成功消息
      const redBallsStr = validRedBalls.map(num => String(num).padStart(2, '0')).join(', ');
      const blueBallStr = String(validBlueBall).padStart(2, '0');
      
      message.success(
        `双色球智能选号完成！红球: ${redBallsStr} | 蓝球: ${blueBallStr}` +
        (doubleBallResult.analysis && doubleBallResult.analysis.luckyIntegration && 
         doubleBallResult.analysis.luckyIntegration.includes("已融入幸运数字") ? " (已融入幸运数字)" : "")
      );
      
      // 如果有幸运数字，显示额外信息
      if (processedLuckyNumbers && processedLuckyNumbers.trim() !== '') {
        message.info(`算法已尝试融入您的幸运数字，红球范围1-33，蓝球范围1-16`);
      }
      
      // 更新可拖拽结果状态：移除已使用的球
      if (result && result.finalResult) {
        const selectedBalls = [...validRedBalls, validBlueBall];
        // 获取当前可用的球列表
        const currentAvailable = availableBalls.length > 0 ? availableBalls : result.finalResult;
        
        // 从可用球中移除已选中的球（只移除确实在可用列表中的球）
        const newAvailableBalls = currentAvailable.filter(ball => !selectedBalls.includes(ball));
        
        // 将选中的球标记为已使用（只包含在计算结果中的球）
        const newUsedBalls = selectedBalls.filter(ball => result.finalResult.includes(ball));
        
        // 智能选号可能生成不在原始计算结果中的球号，这是正常的
        // 我们只管理原始计算结果中的球，智能选号生成的额外球号不影响计算结果区域
        
        setUsedBalls(newUsedBalls);
        setAvailableBalls(newAvailableBalls);
        
        console.log('智能选号后状态更新:', {
          selectedBalls,
          selectedFromOriginal: newUsedBalls, // 来自原始计算结果的选中球
          selectedFromSmart: selectedBalls.filter(ball => !result.finalResult.includes(ball)), // 智能选号额外生成的球
          newAvailableBalls: newAvailableBalls.length,
          originalAvailable: currentAvailable.length,
          note: '智能选号可能生成不在原始计算结果中的球号，这是正常的'
        });
      }
      
    } catch (error) {
      console.error('智能选号失败:', error);
      errorMonitor.logError('智能选号失败', error, { 
        formValues, 
        processedLuckyNumbers,
        context: 'handleSmartSelection' 
      });
      message.error(`智能选号失败: ${error.message || '未知错误'}`);
    }
  };

  // 清空选号
  const handleClearSelection = () => {
    setRedBalls([null, null, null, null, null, null]);
    setBlueBall(null);
    
    // 恢复可拖拽结果：将已使用的球重新加入可拖拽列表
    if (result && result.finalResult) {
      setUsedBalls([]);
      setAvailableBalls(result.finalResult);
    }
  };

  // 加载选号记录
  const loadSelections = async () => {
    setLoadingSelections(true);
    try {
      // 使用统一的选号记录表，获取所有记录然后筛选计算器来源
      const allSelections = await DatabaseService.getAllPickingRecords();
      
      // 筛选计算器来源的记录
      const calculatorSelections = allSelections.filter(record => record.source === 'calculator');
      
      // 转换为旧格式以兼容现有界面
      const formattedSelections = calculatorSelections.map(record => ({
        id: record.id,
        redBalls: record.redBalls,
        blueBall: record.blueBalls[0], // 蓝球数组的第一个元素
        note: record.note,
        createTime: record.createTime,
        timestamp: record.timestamp
      }));
      
      setSelections(formattedSelections);
      console.log(`计算器页面加载了 ${formattedSelections.length} 条选号记录`);
    } catch (error) {
      console.error('加载选号记录失败:', error);
      message.error('加载选号记录失败');
    } finally {
      setLoadingSelections(false);
    }
  };

  // 添加选号到记录
  const handleAddSelection = () => {
    // 检查是否有完整的选号
    const validRedBalls = redBalls.filter(ball => ball !== null);
    if (validRedBalls.length !== 6) {
      message.error('请先选择6个红球');
      return;
    }
    
    if (!blueBall) {
      message.error('请先选择1个蓝球');
      return;
    }
    
    // 显示备注输入框
    setNoteModalVisible(true);
    setCurrentNote('');
  };

  // 确认添加选号记录
  const confirmAddSelection = async () => {
    try {
      const validRedBalls = redBalls.filter(ball => ball !== null);
      
      // 使用统一的选号记录表
      // 参数顺序: redBalls, blueBalls, algorithm, source, note, predicted
      await DatabaseService.addPickingRecord(
        validRedBalls,
        [blueBall],
        'calculator',
        'calculator',
        currentNote,
        false
      );
      
      message.success('选号记录已保存');
      setNoteModalVisible(false);
      setCurrentNote('');
      loadSelections(); // 重新加载记录
    } catch (error) {
      console.error('保存选号记录失败:', error);
      message.error(`保存失败: ${error.message}`);
    }
  };

  // 删除选号记录
  const handleDeleteSelection = async (id) => {
    try {
      // 使用统一的选号记录表删除方法
      await DatabaseService.deletePickingRecord(id);
      message.success('记录已删除');
      loadSelections(); // 重新加载记录
    } catch (error) {
      message.error('删除失败');
    }
  };

  // 检查是否可以显示添加按钮
  const canShowAddButton = () => {
    const validRedBalls = redBalls.filter(ball => ball !== null);
    return validRedBalls.length === 6 && blueBall !== null;
  };

  // 测试诊断功能和智能选号问题
  const handleTestIssues = async () => {
    console.log('=== 开始测试两个问题 ===');
    
    // 测试1: 诊断功能是否使用最新3期
    console.log('\n1. 测试诊断功能历史记录顺序:');
    await testDiagnosisOrder();
    
    // 测试2: 智能选号后计算结果球数量
    console.log('\n2. 测试智能选号后球数量变化:');
    console.log('当前状态:', {
      result: result ? '有计算结果' : '无计算结果',
      availableBalls: availableBalls.length,
      usedBalls: usedBalls.length,
      redBalls: redBalls.filter(ball => ball !== null).length,
      blueBall: blueBall ? '已选择' : '未选择'
    });
    
    if (result && result.finalResult) {
      console.log('计算结果总数:', result.finalResult.length);
      console.log('可拖拽球数:', availableBalls.length);
      console.log('已使用球数:', usedBalls.length);
      console.log('理论上应该相等:', result.finalResult.length, '=', availableBalls.length + usedBalls.length);
      
      if (result.finalResult.length === availableBalls.length + usedBalls.length) {
        console.log('✅ 球数量管理正确');
      } else {
        console.log('❌ 球数量管理有问题');
      }
    } else {
      console.log('请先进行矩阵计算获得结果');
    }
    
    message.info('测试完成，请查看浏览器控制台日志');
  };

  // 诊断当前选择号码的重复度
  const handleDiagnosis = async () => {
    const validRedBalls = redBalls.filter(ball => ball !== null);
    if (validRedBalls.length !== 6) {
      message.error('请先选择6个红球');
      return;
    }
    
    if (!blueBall) {
      message.error('请先选择1个蓝球');
      return;
    }

    setDiagnosisLoading(true);
    try {
      // 获取最近3期的开奖记录
      const recentHistory = await DatabaseService.getRecentLotteryHistory(3);
      
      // 添加调试日志，确认获取的是最新的3期
      console.log('诊断功能获取的历史记录:', recentHistory.map(record => ({
        期号: record.issueno,
        开奖日期: record.opendate,
        创建时间: record.createTime,
        红球: record.number,
        蓝球: record.refernumber
      })));
      
      if (recentHistory.length === 0) {
        message.warning('暂无历史开奖记录，无法进行诊断。请先在历史记录页面同步数据。');
        setDiagnosisLoading(false);
        return;
      }

      // 分析重复度
      const analysis = analyzeDuplication(validRedBalls, blueBall, recentHistory);
      setDiagnosisResult(analysis);
      
      // 如果重复数字大于等于2个，显示警告
      if (analysis.totalDuplicates >= 2) {
        setShowDiagnosisModal(true);
        message.warning(`检测到风险：与前3期开奖号码重复${analysis.totalDuplicates}个数字！`);
      } else {
        message.success(`诊断完成：重复度较低，仅重复${analysis.totalDuplicates}个数字`);
      }
      
    } catch (error) {
      console.error('诊断失败:', error);
      errorMonitor.logError('号码诊断失败', error, { 
        redBalls: validRedBalls, 
        blueBall,
        context: 'handleDiagnosis' 
      });
      message.error('诊断失败，请稍后重试');
    } finally {
      setDiagnosisLoading(false);
    }
  };

  // 分析号码重复度的算法
  const analyzeDuplication = (currentRedBalls, currentBlueBall, historyData) => {
    const analysis = {
      totalDuplicates: 0,
      redDuplicates: 0,
      blueDuplicates: 0,
      duplicateDetails: [],
      riskLevel: 'low',
      suggestions: []
    };

    // 分析每一期的重复情况
    historyData.forEach((record, index) => {
      if (!record.number || !record.refernumber) return;
      
      // 解析历史开奖号码
      const historyNumbers = parseHistoryNumbers(record);
      if (!historyNumbers) return;

      const { redBalls: historyRed, blueBall: historyBlue } = historyNumbers;
      
      // 计算红球重复
      const redMatches = currentRedBalls.filter(ball => historyRed.includes(ball));
      
      // 计算蓝球重复
      const blueMatch = currentBlueBall === historyBlue;
      
      if (redMatches.length > 0 || blueMatch) {
        analysis.duplicateDetails.push({
          period: record.issueno || `第${index + 1}期`,
          date: record.opendate,
          redMatches: redMatches,
          blueMatch: blueMatch,
          totalMatches: redMatches.length + (blueMatch ? 1 : 0)
        });
      }
      
      analysis.redDuplicates += redMatches.length;
      analysis.blueDuplicates += blueMatch ? 1 : 0;
    });

    analysis.totalDuplicates = analysis.redDuplicates + analysis.blueDuplicates;

    // 确定风险等级
    if (analysis.totalDuplicates >= 4) {
      analysis.riskLevel = 'high';
      analysis.suggestions.push('建议重新选择号码，重复度过高');
    } else if (analysis.totalDuplicates >= 2) {
      analysis.riskLevel = 'medium';
      analysis.suggestions.push('存在一定重复风险，建议调整部分号码');
    } else {
      analysis.riskLevel = 'low';
      analysis.suggestions.push('重复度较低，号码选择合理');
    }

    return analysis;
  };

  // 解析历史开奖号码字符串
  const parseHistoryNumbers = (record) => {
    try {
      // 数据库中的格式：
      // record.number: "03 04 17 19 25 27" (红球，空格分隔)
      // record.refernumber: "14" (蓝球)
      
      if (!record || !record.number || !record.refernumber) {
        console.warn('记录格式不正确:', record);
        return null;
      }
      
      // 解析红球号码
      const redBalls = record.number.split(/\s+/)
        .map(n => parseInt(n.trim()))
        .filter(n => !isNaN(n) && n >= 1 && n <= 33);
        
      // 解析蓝球号码
      const blueBall = parseInt(record.refernumber.trim());
      
      if (redBalls.length === 6 && !isNaN(blueBall) && blueBall >= 1 && blueBall <= 16) {
        return { redBalls, blueBall };
      }
      
      console.warn('解析后的号码格式不正确:', { redBalls, blueBall, record });
      return null;
    } catch (error) {
      console.error('解析历史号码失败:', error, record);
      return null;
    }
  };

  // 拖拽开始
  const handleDragStart = (e, number, source = 'calculation-result') => {
    e.dataTransfer.setData('text/plain', number);
    e.dataTransfer.setData('application/source', source);
    e.dataTransfer.effectAllowed = 'copy';
  };

  // 拖拽到红球区域
  const handleRedBallDrop = (e, index) => {
    e.preventDefault();
    const number = parseInt(e.dataTransfer.getData('text/plain'));
    const source = e.dataTransfer.getData('application/source');
    
    // 验证拖拽来源，只允许来自计算结果或幸运数字
    if (source !== 'calculation-result' && source !== 'lucky-number') {
      message.error('只能拖入计算结果或幸运数字');
      return;
    }
    
    // 验证数字范围
    if (number < 1 || number > 33) {
      message.error('红球范围为1-33，请选择正确的数字');
      return;
    }
    
    // 如果是从计算结果拖入，验证该数字是否在可用球列表中
    if (source === 'calculation-result') {
      const currentAvailable = availableBalls.length > 0 ? availableBalls : (result?.finalResult || []);
      if (!currentAvailable.includes(number)) {
        message.error('该数字不在可拖拽的计算结果中');
        return;
      }
    }
    
    const newRedBalls = [...redBalls];
    const oldBall = newRedBalls[index]; // 记录被替换的球
    
    newRedBalls[index] = number;
    setRedBalls(newRedBalls);
    
    // 如果是从计算结果拖入，更新可拖拽结果状态
    if (source === 'calculation-result') {
      const newUsedBalls = [...usedBalls];
      // 确保使用正确的可用球数组
      let newAvailableBalls = availableBalls.length > 0 ? [...availableBalls] : [...(result?.finalResult || [])];
      
      // 移除新使用的球
      const ballIndex = newAvailableBalls.indexOf(number);
      if (ballIndex > -1) {
        newAvailableBalls.splice(ballIndex, 1);
        newUsedBalls.push(number);
      }
      
      // 如果有被替换的球，将其恢复到可拖拽结果
      if (oldBall !== null && usedBalls.includes(oldBall)) {
        const usedIndex = newUsedBalls.indexOf(oldBall);
        if (usedIndex > -1) {
          newUsedBalls.splice(usedIndex, 1);
          newAvailableBalls.push(oldBall);
          newAvailableBalls.sort((a, b) => a - b); // 保持排序
        }
      }
      
      setUsedBalls(newUsedBalls);
      setAvailableBalls(newAvailableBalls);
    }
    
    message.success(`已将 ${String(number).padStart(2, '0')} 设置为红球 ${index + 1}`);
  };

  // 拖拽到蓝球区域
  const handleBlueBallDrop = (e) => {
    e.preventDefault();
    const number = parseInt(e.dataTransfer.getData('text/plain'));
    const source = e.dataTransfer.getData('application/source');
    
    // 验证拖拽来源，只允许来自计算结果或幸运数字
    if (source !== 'calculation-result' && source !== 'lucky-number') {
      message.error('只能拖入计算结果或幸运数字');
      return;
    }
    
    // 验证数字范围
    if (number < 1 || number > 16) {
      message.error('蓝球范围为1-16，请选择正确的数字');
      return;
    }
    
    // 如果是从计算结果拖入，验证该数字是否在可用球列表中
    if (source === 'calculation-result') {
      const currentAvailable = availableBalls.length > 0 ? availableBalls : (result?.finalResult || []);
      if (!currentAvailable.includes(number)) {
        message.error('该数字不在可拖拽的计算结果中');
        return;
      }
    }
    
    const oldBlueBall = blueBall; // 记录被替换的球
    
    setBlueBall(number);
    
    // 如果是从计算结果拖入，更新可拖拽结果状态
    if (source === 'calculation-result') {
      const newUsedBalls = [...usedBalls];
      // 确保使用正确的可用球数组
      let newAvailableBalls = availableBalls.length > 0 ? [...availableBalls] : [...(result?.finalResult || [])];
      
      // 移除新使用的球
      const ballIndex = newAvailableBalls.indexOf(number);
      if (ballIndex > -1) {
        newAvailableBalls.splice(ballIndex, 1);
        newUsedBalls.push(number);
      }
      
      // 如果有被替换的球，将其恢复到可拖拽结果
      if (oldBlueBall !== null && usedBalls.includes(oldBlueBall)) {
        const usedIndex = newUsedBalls.indexOf(oldBlueBall);
        if (usedIndex > -1) {
          newUsedBalls.splice(usedIndex, 1);
          newAvailableBalls.push(oldBlueBall);
          newAvailableBalls.sort((a, b) => a - b); // 保持排序
        }
      }
      
      setUsedBalls(newUsedBalls);
      setAvailableBalls(newAvailableBalls);
    }
    
    message.success(`已将 ${String(number).padStart(2, '0')} 设置为蓝球`);
  };

  // 允许拖拽
  const handleDragOver = (e) => {
    e.preventDefault();
    e.dataTransfer.dropEffect = 'copy';
  };

  const handleBallDoubleClick = (type, index) => {
    setEditingBall({ type, index });
    const currentValue = type === 'red' ? redBalls[index] : blueBall;
    setEditValue(currentValue ? String(currentValue).padStart(2, '0') : '');
  };

  const handleEditConfirm = () => {
    const value = parseInt(editValue);
    let isValid = false;
    let errorMsg = '';
    
    if (editingBall.type === 'red') {
      // 首先检查数字范围
      if (value < 1 || value > 33) {
        isValid = false;
        errorMsg = '红球范围为1-33，请输入正确的数字';
      } 
      // 然后检查是否在计算结果中
      else if (result && result.finalResult && !result.finalResult.includes(value)) {
        isValid = false;
        errorMsg = `数字 ${String(value).padStart(2, '0')} 不在计算结果中，请选择计算结果中的数字`;
      } else {
        isValid = true;
      }
    } else {
      // 蓝球只检查范围，因为蓝球只有一个
      isValid = value >= 1 && value <= 16;
      errorMsg = '蓝球范围为1-16，请输入正确的数字';
    }
    
    if (isValid) {
      if (editingBall.type === 'red') {
        const newRedBalls = [...redBalls];
        newRedBalls[editingBall.index] = value;
        setRedBalls(newRedBalls);
      } else {
        setBlueBall(value);
      }
      message.success(`已设置为 ${String(value).padStart(2, '0')}`);
    } else {
      message.error(errorMsg);
    }
    setEditingBall(null);
    setEditValue('');
  };

  const handleEditCancel = () => {
    setEditingBall(null);
    setEditValue('');
  };

  const handleCalculate = async (values) => {
    setLoading(true);
    // 使用处理后的幸运数字
    const luckyNumbersToUse = processedLuckyNumbers || values.luckyNumbers || "";
    
    try {
      const calculator = new MatrixCalculator();
      const calculationResult = calculator.calculate(
        values.dateInput || "1",
        luckyNumbersToUse,
        values.weekday || "周二",
        values.shouldReorder !== false
      );
      setResult(calculationResult);
      
      // 初始化可拖拽结果状态
      if (calculationResult && calculationResult.finalResult) {
        setUsedBalls([]);
        setAvailableBalls(calculationResult.finalResult);
      }
    } catch (error) {
      console.error('计算错误:', error);
      errorMonitor.logError('矩阵计算失败', error, { 
        values, 
        luckyNumbersToUse,
        context: 'handleCalculate' 
      });
      message.error(`计算失败: ${error.message || '未知错误'}`);
    } finally {
      setLoading(false);
    }
  };



  // 获取响应式列配置
  const getColSpan = () => {
    if (screenSize === 'mobile') {
      return { left: 24, right: 24 };
    } else if (screenSize === 'tablet') {
      return { left: 12, right: 12 };
    } else {
      return { left: 8, right: 16 };
    }
  };

  // 获取红球网格配置
  const getRedBallColSpan = () => {
    if (screenSize === 'mobile') {
      return 8; // 3个球一行
    } else if (screenSize === 'tablet') {
      return 6; // 4个球一行
    } else {
      return 4; // 6个球一行
    }
  };

  // 获取球体大小
  const getBallSize = () => {
    if (screenSize === 'mobile') {
      return { width: '45px', height: '45px', fontSize: '12px' };
    } else {
      return { width: '50px', height: '50px', fontSize: '14px' };
    }
  };

  const weekdayOptions = [
    { label: "周一", value: "周一" },
    { label: "周二", value: "周二" },
    { label: "周三", value: "周三" },
    { label: "周四", value: "周四" },
    { label: "周五", value: "周五" },
    { label: "周六", value: "周六" },
    { label: "周日", value: "周日" }
  ];



  return (
    <div style={{ 
      padding: isMobile ? 12 : 24,
      maxWidth: '100%',
      overflow: 'hidden'
    }}>
      <Title level={isMobile ? 3 : 2}>
        <CalculatorOutlined /> 双色球智能选号系统
      </Title>
      <Paragraph style={{ fontSize: isMobile ? '14px' : '16px' }}>
        基于时间戳和幸运数字的高级矩阵运算 + 双色球智能选号 (红球1-33，蓝球1-16)
      </Paragraph>

      <Divider />

      {/* 移动端导航提示 */}
      {isMobile && (
        <Card 
          size="small" 
          style={{ 
            marginBottom: 16, 
            background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
            border: 'none'
          }}
        >
          <div style={{ textAlign: 'center', color: 'white' }}>
            <Text style={{ color: 'white', fontSize: '13px' }}>
              📱 移动端操作指南：先设置参数计算 → 再拖拽数字选号
            </Text>
          </div>
        </Card>
      )}

      <Row gutter={isMobile ? [12, 16] : [24, 24]}>
        {/* 左侧：参数设置和红蓝球选择 */}
        <Col span={getColSpan().left} order={isMobile ? 1 : 1}>
          <Space direction="vertical" style={{ width: '100%' }} size={isMobile ? "middle" : "large"}>
            {/* 参数设置卡片 */}
            <Card 
              title={<><SettingOutlined /> {isMobile ? '智能计算参数' : '参数设置'}</>}
              size={isMobile ? "small" : "default"}
            >
              <Form
                form={form}
                layout="vertical"
                onFinish={handleCalculate}
                initialValues={{
                  dateInput: new Date().toISOString().slice(0, 10).replace(/-/g, ''),
                  weekday: "周二",
                  shouldReorder: true
                }}
              >
                <Form.Item
                  label={<><CalendarOutlined /> 日期参数</>}
                  name="dateInput"
                  tooltip="格式：YYYYMMDD (如：20250101) 或输入 1 使用今天"
                >
                  <Input placeholder="20250101 或 1" size={isMobile ? "large" : "middle"} />
                </Form.Item>

                <Form.Item
                  label={<><NumberOutlined /> 幸运数字</>}
                  name="luckyNumbers"
                  tooltip="直接输入数字，系统会自动识别并映射到双色球范围（红球1-33，蓝球1-16）"
                >
                  <Input 
                    placeholder="例如：12456789 或 12 45 67 89（将智能映射到双色球范围）" 
                    onChange={handleLuckyNumbersChange}
                    size={isMobile ? "large" : "middle"}
                  />
                </Form.Item>
                {processedLuckyNumbers && (
                  <div style={{ 
                    marginTop: 8, 
                    marginBottom: 16,
                    padding: isMobile ? 6 : 8, 
                    background: '#f0f0f0', 
                    borderRadius: 4 
                  }}>
                    <Text type="secondary" style={{ fontSize: isMobile ? '11px' : '12px' }}>
                      识别到的幸运数字：(可拖拽到双色球)
                    </Text>
                    <br />
                    <Space wrap style={{ marginTop: 4 }} size={[4, 4]}>
                      {processedLuckyNumbers.split(',').map((num, index) => (
                        <Tag 
                          key={index} 
                          color="green" 
                          size="small"
                          style={{
                            cursor: 'grab',
                            userSelect: 'none',
                            fontSize: isMobile ? '11px' : '12px'
                          }}
                          draggable
                          onDragStart={(e) => handleDragStart(e, parseInt(num), 'lucky-number')}
                        >
                          {num}
                        </Tag>
                      ))}
                    </Space>
                  </div>
                )}

                <Form.Item
                  label="星期"
                  name="weekday"
                >
                  <Select options={weekdayOptions} size={isMobile ? "large" : "middle"} />
                </Form.Item>

                <Form.Item
                  name="shouldReorder"
                  valuePropName="checked"
                >
                  <Checkbox>重新排序幸运数字</Checkbox>
                </Form.Item>

                <Form.Item>
                  <Button 
                    type="primary" 
                    htmlType="submit" 
                    loading={loading}
                    block
                    size={isMobile ? "large" : "large"}
                  >
                    开始计算
                  </Button>
                </Form.Item>
              </Form>
            </Card>
          </Space>
        </Col>

        {/* 右侧：拖拽选号和计算结果 */}
        <Col span={getColSpan().right} order={isMobile ? 2 : 2}>
          <Space direction="vertical" style={{ width: '100%' }} size={isMobile ? "middle" : "large"}>
            {/* 拖拽选号区域 */}
            <Card 
              title={<><SettingOutlined /> {isMobile ? '🎯 拖拽数字选号' : '拖拽选号区域'}</>}
              size={isMobile ? "small" : "default"}
            >
              <Space direction="vertical" style={{ width: '100%' }} size="middle">
                {/* 操作按钮 */}
                <Row gutter={[8, 8]}>
                  <Col span={isMobile ? 12 : 6}>
                    <Button 
                      type="primary" 
                      onClick={handleSmartSelection}
                      size={isMobile ? "large" : "small"}
                      block={isMobile}
                      style={isMobile ? { height: '44px', fontSize: '15px' } : {}}
                    >
                      🎲 智能选号
                    </Button>
                  </Col>
                  <Col span={isMobile ? 12 : 6}>
                    <Button 
                      onClick={handleClearSelection} 
                      size={isMobile ? "large" : "small"}
                      block={isMobile}
                      style={isMobile ? { height: '44px', fontSize: '15px' } : {}}
                    >
                      🗑️ 清空选号
                    </Button>
                  </Col>
                  <Col span={isMobile ? 12 : 6}>
                    <Button 
                      onClick={handleTestIssues}
                      size={isMobile ? "large" : "small"}
                      block={isMobile}
                      style={isMobile ? { height: '44px', fontSize: '15px' } : {}}
                      type="dashed"
                    >
                      🔍 测试问题
                    </Button>
                  </Col>
                  <Col span={isMobile ? 12 : 6}>
                    <Button 
                      onClick={reinitializeDatabase}
                      size={isMobile ? "large" : "small"}
                      block={isMobile}
                      style={isMobile ? { height: '44px', fontSize: '15px' } : {}}
                      type="primary"
                      danger
                    >
                      🔄 修复数据库
                    </Button>
                  </Col>
                </Row>

                {/* 可拖拽的幸运数字 - 球形样式 */}
                {processedLuckyNumbers && (
                  <div style={{ marginBottom: 16 }}>
                    <Text strong style={{ fontSize: isMobile ? '13px' : '14px', color: '#faad14' }}>
                      可拖拽的幸运数字：
                    </Text>
                    <div style={{ marginTop: 12 }}>
                      <Space wrap size={[6, 6]}>
                        {processedLuckyNumbers.split(',').map((num, index) => (
                          <div
                            key={index}
                            draggable
                            onDragStart={(e) => handleDragStart(e, parseInt(num), 'lucky-number')}
                            style={{
                              width: isMobile ? '35px' : '40px',
                              height: isMobile ? '35px' : '40px',
                              borderRadius: '50%',
                              background: 'radial-gradient(circle at 30% 30%, #fff7e6, #ffd666 40%, #faad14 70%, #d48806 100%)',
                              color: 'white',
                              display: 'flex',
                              alignItems: 'center',
                              justifyContent: 'center',
                              fontSize: isMobile ? '10px' : '12px',
                              fontWeight: 'bold',
                              border: '2px solid #d48806',
                              cursor: 'grab',
                              userSelect: 'none',
                              boxShadow: 'inset 0 2px 4px rgba(255,255,255,0.3), inset 0 -2px 4px rgba(0,0,0,0.2), 0 3px 8px rgba(250, 173, 20, 0.3)',
                              transition: 'all 0.2s ease',
                              textShadow: '0 1px 2px rgba(0,0,0,0.3)'
                            }}
                            title={`幸运数字: ${String(num).padStart(2, '0')} (拖拽到选号区)`}
                            onMouseDown={(e) => e.currentTarget.style.transform = 'scale(0.95)'}
                            onMouseUp={(e) => e.currentTarget.style.transform = 'scale(1)'}
                            onMouseLeave={(e) => e.currentTarget.style.transform = 'scale(1)'}
                          >
                            {String(num).padStart(2, '0')}
                          </div>
                        ))}
                      </Space>
                    </div>
                  </div>
                )}

                {/* 可拖拽的计算结果 - 球形样式 */}
                {result && result.finalResult && result.finalResult.length > 0 && (
                  <div style={{ marginBottom: 16 }}>
                    <Text strong style={{ fontSize: isMobile ? '13px' : '14px', color: '#1890ff' }}>
                      可拖拽的计算结果：【{availableBalls.length > 0 ? availableBalls.length : result.finalResult.length}个球】
                    </Text>
                    <div style={{ marginTop: 12 }}>
                      <Space wrap size={[6, 6]}>
                        {(availableBalls.length > 0 ? availableBalls : result.finalResult).slice(0, isMobile ? 15 : 20).map((num, index) => (
                          <div
                            key={index}
                            draggable
                            onDragStart={(e) => handleDragStart(e, num, 'calculation-result')}
                            style={{
                              width: isMobile ? '35px' : '40px',
                              height: isMobile ? '35px' : '40px',
                              borderRadius: '50%',
                              background: 'radial-gradient(circle at 30% 30%, #91d5ff, #40a9ff 40%, #1890ff 70%, #0050b3 100%)',
                              color: 'white',
                              display: 'flex',
                              alignItems: 'center',
                              justifyContent: 'center',
                              fontSize: isMobile ? '10px' : '12px',
                              fontWeight: 'bold',
                              border: '2px solid #0050b3',
                              cursor: 'grab',
                              userSelect: 'none',
                              boxShadow: 'inset 0 2px 4px rgba(255,255,255,0.3), inset 0 -2px 4px rgba(0,0,0,0.2), 0 3px 8px rgba(24, 144, 255, 0.3)',
                              transition: 'all 0.2s ease',
                              textShadow: '0 1px 2px rgba(0,0,0,0.3)'
                            }}
                            title={`计算结果: ${String(num).padStart(2, '0')} (拖拽到选号区)`}
                            onMouseDown={(e) => e.currentTarget.style.transform = 'scale(0.95)'}
                            onMouseUp={(e) => e.currentTarget.style.transform = 'scale(1)'}
                            onMouseLeave={(e) => e.currentTarget.style.transform = 'scale(1)'}
                          >
                            {String(num).padStart(2, '0')}
                          </div>
                        ))}
                      </Space>
                    </div>
                  </div>
                )}



                {/* 红球选择 */}
                <div>
                  <Text strong style={{ 
                    color: '#ff4d4f', 
                    fontSize: isMobile ? '14px' : '16px',
                    display: 'block',
                    marginBottom: '8px'
                  }}>
                    {isMobile ? '🔴 红球选择 (6个)' : '红球选择 (6个) - 拖拽数字到此处，双击编辑'}
                  </Text>
                  {isMobile && (
                    <Text type="secondary" style={{ fontSize: '12px', display: 'block', marginBottom: '8px' }}>
                      拖拽上方数字到此处，双击编辑
                    </Text>
                  )}
                  <Row gutter={[8, 8]} style={{ marginTop: 12 }}>
                    {redBalls.map((ball, index) => (
                      <Col span={getRedBallColSpan()} key={index}>
                        <div
                          onDrop={(e) => handleRedBallDrop(e, index)}
                          onDragOver={handleDragOver}
                          style={{
                            display: 'flex',
                            justifyContent: 'center',
                            alignItems: 'center',
                            minHeight: isMobile ? '55px' : '60px'
                          }}
                        >
                          {editingBall && editingBall.type === 'red' && editingBall.index === index ? (
                            <Input
                              value={editValue}
                              onChange={(e) => setEditValue(e.target.value)}
                              onPressEnter={handleEditConfirm}
                              onBlur={handleEditCancel}
                              style={{ 
                                width: isMobile ? '45px' : '50px', 
                                textAlign: 'center' 
                              }}
                              maxLength={2}
                              autoFocus
                            />
                          ) : (
                            <div
                              onDoubleClick={() => handleBallDoubleClick('red', index)}
                              style={{
                                 width: getBallSize().width,
                                 height: getBallSize().height,
                                 borderRadius: '50%',
                                 background: ball ? 
                                   'radial-gradient(circle at 30% 30%, #ff7875, #ff4d4f 40%, #d4380d 70%, #ad2102 100%)' : 
                                   'radial-gradient(circle at 30% 30%, #ffffff, #f5f5f5 40%, #d9d9d9 70%, #bfbfbf 100%)',
                                 color: ball ? 'white' : '#666',
                                 display: 'flex',
                                 alignItems: 'center',
                                 justifyContent: 'center',
                                 fontSize: getBallSize().fontSize,
                                 fontWeight: 'bold',
                                 border: ball ? '2px solid #ad2102' : '2px solid #d9d9d9',
                                 cursor: 'pointer',
                                 userSelect: 'none',
                                 boxShadow: ball ? 
                                   'inset 0 2px 4px rgba(255,255,255,0.3), inset 0 -2px 4px rgba(0,0,0,0.2), 0 4px 12px rgba(255, 77, 79, 0.4)' : 
                                   'inset 0 2px 4px rgba(255,255,255,0.8), inset 0 -2px 4px rgba(0,0,0,0.1), 0 2px 6px rgba(0,0,0,0.1)',
                                 transition: 'all 0.2s ease',
                                 position: 'relative',
                                 textShadow: ball ? '0 1px 2px rgba(0,0,0,0.3)' : '0 1px 1px rgba(0,0,0,0.1)'
                               }}
                              title={ball ? `红球${index + 1}: ${String(ball).padStart(2, '0')} (双击编辑)` : `红球${index + 1} (双击编辑)`}
                            >
                              {ball ? String(ball).padStart(2, '0') : `红${index + 1}`}
                            </div>
                          )}
                        </div>
                      </Col>
                    ))}
                  </Row>
                </div>

                {/* 蓝球选择 */}
                <div>
                  <Text strong style={{ 
                    color: '#1890ff', 
                    fontSize: isMobile ? '14px' : '16px',
                    display: 'block',
                    marginBottom: '8px'
                  }}>
                    {isMobile ? '🔵 蓝球选择 (1个)' : '蓝球选择 (1个) - 拖拽数字到此处，双击编辑'}
                  </Text>
                  {isMobile && (
                    <Text type="secondary" style={{ fontSize: '12px', display: 'block', marginBottom: '8px' }}>
                      拖拽数字到此处，双击编辑
                    </Text>
                  )}
                  <Row style={{ marginTop: 12 }}>
                    <Col span={getRedBallColSpan()}>
                      <div
                        onDrop={handleBlueBallDrop}
                        onDragOver={handleDragOver}
                        style={{
                          display: 'flex',
                          justifyContent: 'center',
                          alignItems: 'center',
                          minHeight: isMobile ? '55px' : '60px'
                        }}
                      >
                        {editingBall && editingBall.type === 'blue' ? (
                          <Input
                            value={editValue}
                            onChange={(e) => setEditValue(e.target.value)}
                            onPressEnter={handleEditConfirm}
                            onBlur={handleEditCancel}
                            style={{ 
                              width: isMobile ? '45px' : '50px', 
                              textAlign: 'center' 
                            }}
                            maxLength={2}
                            autoFocus
                          />
                        ) : (
                          <div
                            onDoubleClick={() => handleBallDoubleClick('blue', 0)}
                            style={{
                               width: getBallSize().width,
                               height: getBallSize().height,
                               borderRadius: '50%',
                               background: blueBall ? 
                                 'radial-gradient(circle at 30% 30%, #69c0ff, #1890ff 40%, #0958d9 70%, #003a8c 100%)' : 
                                 'radial-gradient(circle at 30% 30%, #ffffff, #f5f5f5 40%, #d9d9d9 70%, #bfbfbf 100%)',
                               color: blueBall ? 'white' : '#666',
                               display: 'flex',
                               alignItems: 'center',
                               justifyContent: 'center',
                               fontSize: getBallSize().fontSize,
                               fontWeight: 'bold',
                               border: blueBall ? '2px solid #003a8c' : '2px solid #d9d9d9',
                               cursor: 'pointer',
                               userSelect: 'none',
                               boxShadow: blueBall ? 
                                 'inset 0 2px 4px rgba(255,255,255,0.3), inset 0 -2px 4px rgba(0,0,0,0.2), 0 4px 12px rgba(24, 144, 255, 0.4)' : 
                                 'inset 0 2px 4px rgba(255,255,255,0.8), inset 0 -2px 4px rgba(0,0,0,0.1), 0 2px 6px rgba(0,0,0,0.1)',
                               transition: 'all 0.2s ease',
                               position: 'relative',
                               textShadow: blueBall ? '0 1px 2px rgba(0,0,0,0.3)' : '0 1px 1px rgba(0,0,0,0.1)'
                             }}
                            title={blueBall ? `蓝球: ${String(blueBall).padStart(2, '0')} (双击编辑)` : '蓝球 (双击编辑)'}
                          >
                            {blueBall ? String(blueBall).padStart(2, '0') : '蓝球'}
                          </div>
                        )}
                      </div>
                    </Col>
                  </Row>
                </div>

                {/* 选号统计 */}
                <Row gutter={16}>
                  <Col span={8}>
                    <Statistic
                      title="已选红球"
                      value={redBalls.filter(ball => ball !== null).length}
                      suffix="/ 6"
                      valueStyle={{ color: '#ff4d4f', fontSize: '16px' }}
                    />
                  </Col>
                  <Col span={8}>
                    <Statistic
                      title="已选蓝球"
                      value={blueBall ? 1 : 0}
                      suffix="/ 1"
                      valueStyle={{ color: '#1890ff', fontSize: '16px' }}
                    />
                  </Col>
                </Row>
              </Space>
            </Card>

            {/* 添加选择按钮和诊断按钮 */}
            {canShowAddButton() && (
              <Card size="small">
                <Space direction="vertical" style={{ width: '100%' }} size="small">
                  <Row gutter={8}>
                    <Col span={16}>
                      <Button 
                        type="primary" 
                        icon={<PlusOutlined />}
                        onClick={handleAddSelection}
                        size="large"
                        block
                        style={{ 
                          background: 'linear-gradient(135deg, #52c41a, #73d13d)',
                          borderColor: '#52c41a',
                          fontWeight: 'bold'
                        }}
                      >
                        添加选择到记录
                      </Button>
                    </Col>
                    <Col span={8}>
                      <Button 
                        type="default"
                        icon={(diagnosisResult && diagnosisResult.riskLevel === 'medium') || (diagnosisResult && diagnosisResult.riskLevel === 'high') ? 
                          <ExclamationCircleOutlined /> : <CheckCircleOutlined />}
                        onClick={handleDiagnosis}
                        loading={diagnosisLoading}
                        size="large"
                        block
                        style={{ 
                          borderColor: diagnosisResult && diagnosisResult.riskLevel === 'medium' ? '#faad14' : 
                                      diagnosisResult && diagnosisResult.riskLevel === 'high' ? '#ff4d4f' : '#52c41a',
                          color: diagnosisResult && diagnosisResult.riskLevel === 'medium' ? '#faad14' : 
                                diagnosisResult && diagnosisResult.riskLevel === 'high' ? '#ff4d4f' : '#52c41a'
                        }}
                      >
                        诊断
                      </Button>
                    </Col>
                  </Row>
                  
                  {/* 诊断结果显示区域 */}
                  {diagnosisResult && (
                    <div style={{ 
                      padding: '8px 12px',
                      borderRadius: '6px',
                      backgroundColor: diagnosisResult.riskLevel === 'high' ? '#fff2f0' : 
                                      diagnosisResult.riskLevel === 'medium' ? '#fffbe6' : '#f6ffed',
                      border: `1px solid ${diagnosisResult.riskLevel === 'high' ? '#ffccc7' : 
                                            diagnosisResult.riskLevel === 'medium' ? '#ffe58f' : '#b7eb8f'}`
                    }}>
                      <Text 
                        style={{ 
                          fontSize: '12px',
                          color: diagnosisResult.riskLevel === 'high' ? '#ff4d4f' : 
                                diagnosisResult.riskLevel === 'medium' ? '#faad14' : '#52c41a',
                          fontWeight: 'bold'
                        }}
                      >
                        {diagnosisResult.riskLevel === 'high' && '⚠️ 高风险重复'}
                        {diagnosisResult.riskLevel === 'medium' && '⚠️ 风险重复'}
                        {diagnosisResult.riskLevel === 'low' && '✅ 重复度较低'}
                        ：与前3期重复 {diagnosisResult.totalDuplicates} 个数字
                      </Text>
                      <br />
                      <Text style={{ fontSize: '11px', color: '#666' }}>
                        {diagnosisResult.suggestions[0]}
                      </Text>
                    </div>
                  )}
                </Space>
              </Card>
            )}

            {/* 选号记录列表 */}
            <Card 
              title={
                <Space>
                  <HistoryOutlined />
                  <span>选号记录</span>
                  <Tag color="blue">{selections.length} 条记录</Tag>
                </Space>
              }
              size="small"
            >
              {selections.length === 0 ? (
                <Empty 
                  description="暂无选号记录"
                  image={Empty.PRESENTED_IMAGE_SIMPLE}
                  style={{ padding: '20px 0' }}
                />
              ) : (
                <List
                  dataSource={selections}
                  loading={loadingSelections}
                  pagination={{
                    pageSize: 5,
                    size: 'small',
                    showSizeChanger: false,
                    showQuickJumper: false
                  }}
                  renderItem={(item, index) => (
                    <List.Item
                      actions={[
                        <Popconfirm
                          title="确定删除这条记录吗？"
                          onConfirm={() => handleDeleteSelection(item.id)}
                          okText="确定"
                          cancelText="取消"
                        >
                          <Button 
                            type="text" 
                            danger 
                            icon={<DeleteOutlined />}
                            size="small"
                          >
                            删除
                          </Button>
                        </Popconfirm>
                      ]}
                    >
                      <List.Item.Meta
                        title={
                          <Space>
                            <Text strong style={{ fontSize: '14px' }}>
                              第 {selections.length - index} 注
                            </Text>
                            <Text type="secondary" style={{ fontSize: '12px' }}>
                              {new Date(item.createTime).toLocaleString()}
                            </Text>
                          </Space>
                        }
                        description={
                          <div>
                            {/* 球体显示 */}
                            <div style={{ marginBottom: item.note ? 8 : 0 }}>
                              <Space size={4}>
                                {/* 红球 */}
                                {item.redBalls.map((ball, ballIndex) => (
                                  <div
                                    key={ballIndex}
                                    style={{
                                      width: 22,
                                      height: 22,
                                      borderRadius: '50%',
                                      backgroundColor: '#ff4d4f',
                                      color: 'white',
                                      display: 'flex',
                                      alignItems: 'center',
                                      justifyContent: 'center',
                                      fontSize: '10px',
                                      fontWeight: 'bold'
                                    }}
                                  >
                                    {String(ball).padStart(2, '0')}
                                  </div>
                                ))}
                                
                                {/* 蓝球 */}
                                <div
                                  style={{
                                    width: 24,
                                    height: 24,
                                    borderRadius: '50%',
                                    backgroundColor: '#1890ff',
                                    color: 'white',
                                    display: 'flex',
                                    alignItems: 'center',
                                    justifyContent: 'center',
                                    fontSize: '11px',
                                    fontWeight: 'bold',
                                    marginLeft: 4
                                  }}
                                >
                                  {String(item.blueBall).padStart(2, '0')}
                                </div>
                              </Space>
                            </div>
                            
                            {/* 备注 */}
                            {item.note && (
                              <div>
                                <Text type="secondary" style={{ fontSize: '11px' }}>
                                  备注：{item.note}
                                </Text>
                              </div>
                            )}
                          </div>
                        }
                      />
                    </List.Item>
                  )}
                />
              )}
            </Card>

            {/* 详细计算过程 - 已隐藏 */}
            {/* {result && (
              <Card title="详细计算过程">
                  <Collapse>
                    <Panel header="时间戳信息" key="timestamps">
                      <Row gutter={16}>
                        <Col span={8}>
                          <Card size="small" title="当前时间戳">
                            <Text code>{result.timestamps[0]}</Text>
                            <br />
                            <Text type="secondary">
                              {new Date(result.timestamps[0]).toLocaleString()}
                            </Text>
                          </Card>
                        </Col>
                        <Col span={8}>
                          <Card size="small" title="未来时间戳">
                            <Text code>{result.timestamps[1]}</Text>
                            <br />
                            <Text type="secondary">
                              {new Date(result.timestamps[1]).toLocaleString()}
                            </Text>
                          </Card>
                        </Col>
                        <Col span={8}>
                          <Card size="small" title="过去时间戳">
                            <Text code>{result.timestamps[2]}</Text>
                            <br />
                            <Text type="secondary">
                              {new Date(result.timestamps[2]).toLocaleString()}
                            </Text>
                          </Card>
                        </Col>
                      </Row>
                    </Panel>

                    <Panel header="初始矩阵 A, B, C" key="matrices">
                      <Row gutter={16}>
                        <Col span={8}>
                          <MatrixDisplay matrix={result.matrices.A} title="矩阵 A" />
                        </Col>
                        <Col span={8}>
                          <MatrixDisplay matrix={result.matrices.B} title="矩阵 B" />
                        </Col>
                        <Col span={8}>
                          <MatrixDisplay matrix={result.matrices.C} title="矩阵 C" />
                        </Col>
                      </Row>
                    </Panel>

                    <Panel header="计算过程矩阵" key="calculations">
                      <Row gutter={16}>
                        <Col span={12}>
                          <MatrixDisplay matrix={result.calculations.C} title="C = A + B" />
                        </Col>
                        <Col span={12}>
                          <MatrixDisplay matrix={result.calculations.D} title="D = B - C" />
                        </Col>
                      </Row>
                      <Row gutter={16}>
                        <Col span={12}>
                          <MatrixDisplay matrix={result.calculations.E} title="E = B * A" />
                        </Col>
                        <Col span={12}>
                          <MatrixDisplay matrix={result.calculations.F} title="F = C / A" />
                        </Col>
                      </Row>
                      <Row gutter={16}>
                        <Col span={12}>
                          <MatrixDisplay matrix={result.calculations.G} title="G (混合矩阵)" />
                        </Col>
                        <Col span={12}>
                          <MatrixDisplay matrix={result.calculations.T} title="T = C + D - E * F / G" />
                        </Col>
                      </Row>
                    </Panel>
                </Collapse>
              </Card>
            )} */}
          </Space>
        </Col>
      </Row>

      {/* 最终选号结果 - 放在最下方，小一点 */}
      <Row style={{ marginTop: 24 }}>
        <Col span={24}>
          <Card 
            size="small" 
            title={<><EyeOutlined /> 最终选号结果</>}
            style={{ backgroundColor: '#fafafa' }}
          >
            <Row gutter={16} align="middle">
              {/* 红球显示 */}
              <Col span={18}>
                <div>
                  <Text strong style={{ color: '#ff4d4f', fontSize: '14px' }}>红球：</Text>
                  <Space style={{ marginLeft: 8 }}>
                    {redBalls.map((ball, index) => (
                      <div
                        key={index}
                        style={{
                          width: 28,
                          height: 28,
                          borderRadius: '50%',
                          backgroundColor: ball ? '#ff4d4f' : '#f5f5f5',
                          color: ball ? 'white' : '#ccc',
                          display: 'flex',
                          alignItems: 'center',
                          justifyContent: 'center',
                          fontSize: '12px',
                          fontWeight: 'bold',
                          border: '1px solid #ff4d4f'
                        }}
                      >
                        {ball ? String(ball).padStart(2, '0') : '--'}
                      </div>
                    ))}
                  </Space>
                </div>
              </Col>

              {/* 蓝球显示 */}
              <Col span={6}>
                <div>
                  <Text strong style={{ color: '#1890ff', fontSize: '14px' }}>蓝球：</Text>
                  <div
                    style={{
                      width: 32,
                      height: 32,
                      borderRadius: '50%',
                      backgroundColor: blueBall ? '#1890ff' : '#f5f5f5',
                      color: blueBall ? 'white' : '#ccc',
                      display: 'inline-flex',
                      alignItems: 'center',
                      justifyContent: 'center',
                      fontSize: '14px',
                      fontWeight: 'bold',
                      border: '1px solid #1890ff',
                      marginLeft: 8
                    }}
                  >
                    {blueBall ? String(blueBall).padStart(2, '0') : '--'}
                  </div>
                </div>
              </Col>
            </Row>
          </Card>
        </Col>
      </Row>

      {/* 备注输入Modal */}
      <Modal
        title="添加选号记录"
        open={noteModalVisible}
        onOk={confirmAddSelection}
        onCancel={() => {
          setNoteModalVisible(false);
          setCurrentNote('');
        }}
        okText="保存"
        cancelText="取消"
        width={400}
      >
        <div style={{ marginBottom: 16 }}>
          <Text strong>当前选号：</Text>
          <div style={{ marginTop: 8, padding: 12, background: '#f5f5f5', borderRadius: 6 }}>
            {/* 红球预览 */}
            <div style={{ marginBottom: 8 }}>
              <Text strong style={{ color: '#ff4d4f', fontSize: '12px' }}>红球：</Text>
              <Space style={{ marginLeft: 8 }} size={4}>
                {redBalls.filter(ball => ball !== null).map((ball, index) => (
                  <div
                    key={index}
                    style={{
                      width: 24,
                      height: 24,
                      borderRadius: '50%',
                      backgroundColor: '#ff4d4f',
                      color: 'white',
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'center',
                      fontSize: '11px',
                      fontWeight: 'bold'
                    }}
                  >
                    {String(ball).padStart(2, '0')}
                  </div>
                ))}
              </Space>
            </div>
            
            {/* 蓝球预览 */}
            <div>
              <Text strong style={{ color: '#1890ff', fontSize: '12px' }}>蓝球：</Text>
              <div
                style={{
                  width: 28,
                  height: 28,
                  borderRadius: '50%',
                  backgroundColor: '#1890ff',
                  color: 'white',
                  display: 'inline-flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  fontSize: '12px',
                  fontWeight: 'bold',
                  marginLeft: 8
                }}
              >
                {blueBall ? String(blueBall).padStart(2, '0') : '--'}
              </div>
            </div>
          </div>
        </div>
        
        <div>
          <Text strong>备注（可选）：</Text>
          <Input.TextArea
            value={currentNote}
            onChange={(e) => setCurrentNote(e.target.value)}
            placeholder="为这注选号添加备注..."
            rows={3}
            maxLength={100}
            showCount
            style={{ marginTop: 8 }}
          />
        </div>
      </Modal>

      {/* 诊断详情Modal */}
      <Modal
        title={
          <Space>
            <ExclamationCircleOutlined style={{ color: '#faad14' }} />
            <span>号码重复度诊断报告</span>
          </Space>
        }
        open={showDiagnosisModal}
        onOk={() => setShowDiagnosisModal(false)}
        onCancel={() => setShowDiagnosisModal(false)}
        okText="知道了"
        cancelText="关闭"
        width={600}
        footer={[
          <Button key="close" onClick={() => setShowDiagnosisModal(false)}>
            关闭
          </Button>
        ]}
      >
        {diagnosisResult && (
          <div>
            {/* 总体风险评估 */}
            <Card size="small" style={{ marginBottom: 16 }}>
              <Row gutter={16} align="middle">
                <Col span={4}>
                  <div style={{ textAlign: 'center' }}>
                    {diagnosisResult.riskLevel === 'high' && 
                      <ExclamationCircleOutlined style={{ fontSize: 32, color: '#ff4d4f' }} />}
                    {diagnosisResult.riskLevel === 'medium' && 
                      <ExclamationCircleOutlined style={{ fontSize: 32, color: '#faad14' }} />}
                    {diagnosisResult.riskLevel === 'low' && 
                      <CheckCircleOutlined style={{ fontSize: 32, color: '#52c41a' }} />}
                  </div>
                </Col>
                <Col span={20}>
                  <div>
                    <Title level={5} style={{ margin: 0, marginBottom: 4 }}>
                      {diagnosisResult.riskLevel === 'high' && '高风险重复'}
                      {diagnosisResult.riskLevel === 'medium' && '中等风险重复'}
                      {diagnosisResult.riskLevel === 'low' && '重复度较低'}
                    </Title>
                    <Text type="secondary">
                      与前3期开奖号码共重复 <Text strong style={{ color: '#ff4d4f' }}>
                        {diagnosisResult.totalDuplicates}
                      </Text> 个数字
                      （红球重复 {diagnosisResult.redDuplicates} 个，蓝球重复 {diagnosisResult.blueDuplicates} 个）
                    </Text>
                  </div>
                </Col>
              </Row>
            </Card>

            {/* 建议 */}
            <Card size="small" style={{ marginBottom: 16 }}>
              <Title level={5} style={{ margin: 0, marginBottom: 8 }}>
                <SettingOutlined /> 建议
              </Title>
              <Text>{diagnosisResult.suggestions[0]}</Text>
            </Card>

            {/* 详细重复情况 */}
            {diagnosisResult.duplicateDetails.length > 0 && (
              <Card size="small">
                <Title level={5} style={{ margin: 0, marginBottom: 12 }}>
                  <HistoryOutlined /> 详细重复情况
                </Title>
                <List
                  size="small"
                  dataSource={diagnosisResult.duplicateDetails}
                  renderItem={(detail) => (
                    <List.Item>
                      <List.Item.Meta
                        title={
                          <Space>
                            <Text strong>{detail.period}</Text>
                            <Text type="secondary" style={{ fontSize: '12px' }}>
                              {detail.date}
                            </Text>
                            <Tag color={detail.totalMatches >= 3 ? 'red' : detail.totalMatches >= 2 ? 'orange' : 'blue'}>
                              重复 {detail.totalMatches} 个
                            </Tag>
                          </Space>
                        }
                        description={
                          <div>
                            {detail.redMatches.length > 0 && (
                              <div style={{ marginBottom: 4 }}>
                                <Text style={{ fontSize: '12px' }}>
                                  红球重复：
                                  <Space size={4} style={{ marginLeft: 4 }}>
                                    {detail.redMatches.map((ball, index) => (
                                      <Tag key={index} color="red" style={{ fontSize: '10px', padding: '0 4px' }}>
                                        {String(ball).padStart(2, '0')}
                                      </Tag>
                                    ))}
                                  </Space>
                                </Text>
                              </div>
                            )}
                            {detail.blueMatch && (
                              <div>
                                <Text style={{ fontSize: '12px' }}>
                                  蓝球重复：
                                  <Tag color="blue" style={{ fontSize: '10px', padding: '0 4px', marginLeft: 4 }}>
                                    {String(detail.blueMatch).padStart(2, '0')}
                                  </Tag>
                                </Text>
                              </div>
                            )}
                          </div>
                        }
                      />
                    </List.Item>
                  )}
                />
              </Card>
            )}

            {/* 无重复情况 */}
            {diagnosisResult.duplicateDetails.length === 0 && (
              <Card size="small">
                <div style={{ textAlign: 'center', padding: '20px 0' }}>
                  <CheckCircleOutlined style={{ fontSize: 48, color: '#52c41a', marginBottom: 16 }} />
                  <div>
                    <Title level={4} style={{ color: '#52c41a' }}>恭喜！</Title>
                    <Text type="secondary">您选择的号码与前3期开奖号码无重复，选号合理！</Text>
                  </div>
                </div>
              </Card>
            )}
          </div>
        )}
      </Modal>
    </div>
  );
};

export default Calculator;